package com.ys.controller.api.base;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.base.TbUserMonthPerformance;
import com.ys.entity.sys.YsCol;
import com.ys.service.base.TbUserMonthPerformanceService;
import com.ys.service.base.TbUserPaySlipService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 员工月度绩效信息
 */
@Controller
@RequestMapping("/api/inter/tbUserMonthPerformance")
public class ApiInterTbUserMonthPerformanceController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTbUserMonthPerformanceController.class);

    @Autowired
    private CommonApiService<TbUserMonthPerformance> commonApiService;

    @Autowired
    private TbUserMonthPerformanceService tbUserMonthPerformanceService;

    @Autowired
    private TbUserPaySlipService tbUserPaySlipService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TbUserMonthPerformance setSeachSql(TbUserMonthPerformance cond){
        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表
                .addField("(U.UserId + '/' + U.UserName) AS _ys_nameLinked")//工号/姓名

                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = U.OrgId")//用户所属机构

                .addField("CASE WHEN A.AttendanceStatus IS NOT NULL AND A.AttendanceStatus !=0 THEN '已导入' ELSE '未导入' END attendanceImportStatus")//考勤状态


                .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表
                .addField("O.OrgName AS orgName");//所属公司

        //绩效申报状态
        cond.addLeftJoin("TB_UserMonthPerformanceReportItem RI ON RI.MonthPerformanceId = A.Id AND 1=1")
                .addLeftJoin("TB_UserMonthPerformanceReport R ON R.Bid = RI.Pbid")
                .addField("CASE WHEN RI.Id IS NOT NULL AND R.EffectStock = 1 THEN '已申报' ELSE '未申报' END reportStatus")//绩效申报状态

                .addField("CASE WHEN RI.Id IS NOT NULL AND R.EffectStock = 1 THEN RI.HrPerformancePoint ELSE NULL END  hrPerformancePointByReport")//部门绩效评分
                .addField("CASE WHEN RI.Id IS NOT NULL AND R.EffectStock = 1 THEN RI.HrPerformanceContent ELSE '' END hrPerformanceContentByReport")//部门评价内容
                .addField("CASE WHEN RI.Id IS NOT NULL AND R.EffectStock = 1 THEN RI.JobBonus ELSE NULL END jobBonus")//岗位提奖
                .addField("CASE WHEN RI.Id IS NOT NULL AND R.EffectStock = 1 THEN RI.JobBonusExplain ELSE '' END jobBonusExplain");///岗位提奖说明

        //考勤状态
        //cond.addLeftJoin("TB_UserAttendance UA ON A.UserAttendanceId = UA.Id AND 1=1")
                //.addField("CASE WHEN A.UserAttendanceId IS NOT NULL THEN '已导入' ELSE '未导入' END attendanceImportStatus");//考勤状态
        //信息状态
        cond.addLeftJoin("TB_UserPaySlip PS ON PS.MonthPerformanceId = A.Id AND 1=1")
                .addField("CASE WHEN PS.Id IS NOT NULL THEN '已生成' ELSE '未生成' END paySlipStatus");//信息状态

        //cond.where("R.EffectStock = 1");
        //排序
        cond.setOrderby("A.UpdateTime DESC");
        cond = commonApiService.dataAuth(MenuId.TB_UserMonthPerformance, cond);
        return cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tbUserMonthPerformance:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TbUserMonthPerformance cond,String conditions
    ){
        try {
            TbUserMonthPerformance newCond = new TbUserMonthPerformance();
            newCond.setPage(cond._ys_page);
            newCond.setSize(cond._ys_size);

            String whereString =setWhereStr(conditions);
            newCond.where(whereString);
            newCond = setSeachSql(newCond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(newCond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    public String setWhereStr(String conditions){
        String pointMonth = ConditionUtil.getConditionValue(conditions, "pointMonth");//评定年月
        String userName = ConditionUtil.getConditionValue(conditions, "_ys_nameLinked");//工号/姓名
        String userState = ConditionUtil.getConditionValue(conditions, "userState");//员工状态
        String deptName = ConditionUtil.getConditionValue(conditions, "deptName");//部门
        String orgName = ConditionUtil.getConditionValue(conditions, "orgName");//所属公司
        String reportStatus = ConditionUtil.getConditionValue(conditions, "reportStatus");//绩效申报状态
        String attendanceImportStatus = ConditionUtil.getConditionValue(conditions, "attendanceImportStatus");//考勤状态
        String paySlipStatus = ConditionUtil.getConditionValue(conditions, "paySlipStatus");//信息状态
        String whereString = "1=1 ";
        if(pointMonth!=null && !"".equals(pointMonth)){
            whereString += " AND A.PointMonth = '"+pointMonth+"' ";
        }
        if(userName!=null && !"".equals(userName)){
            whereString += " AND ( U.UserId Like '%"+userName+"%' OR U.UserName Like '%"+userName+"%' )";
        }
        if(userState!=null && !"".equals(userState)){
            whereString += " AND UAS.UserState =  "+userState+" ";
        }
        if(deptName!=null && !"".equals(deptName)){
            whereString += " AND U.DeptName Like '%"+deptName+"%' ";
        }
        if(orgName!=null && !"".equals(orgName)){
            whereString += " AND O.OrgName Like '%"+orgName+"%' ";
        }
        if(reportStatus!=null && !"".equals(reportStatus)){
            if("已申报".equals(reportStatus)){
                whereString += " AND A.UserAttendanceId IS NOT NULL AND R.EffectStock = 1 ";
            }else {
                whereString += " AND A.UserAttendanceId IS NULL OR R.EffectStock = 0 ";
            }
        }
        if(attendanceImportStatus!=null && !"".equals(attendanceImportStatus)){
            //whereString += " AND A.AttendanceStatus = '"+attendanceImportStatus+"' ";

            if("已导入".equals(attendanceImportStatus)){
                whereString += " AND A.AttendanceStatus IN (1,2) ";
            }else {
                whereString += " AND A.AttendanceStatus = 0  ";
            }
        }
        if(paySlipStatus!=null && !"".equals(paySlipStatus)){
            if("已生成".equals(paySlipStatus)){
                whereString += " AND PS.Id IS NOT NULL ";
            }else {
                whereString += " AND PS.Id IS NULL ";
            }
        }
        return whereString;
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TbUserMonthPerformance cond,String conditions){
        try {
            TbUserMonthPerformance newCond = new TbUserMonthPerformance();
            newCond.setPage(0).setSize(999999);
            String whereString =setWhereStr(conditions);
            newCond = setSeachSql(newCond);
            newCond.where(whereString);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TB_UserMonthPerformance)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = newCond.queryMap();

            //处理数据
            ExportExcelUtils<TbUserMonthPerformance> util = new ExportExcelUtils<>(new TbUserMonthPerformance());
            String toFilePath = util.exportExcel(listData, listField, "员工月度绩效信息");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 编辑
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //编辑
            return tbUserMonthPerformanceService.save(params,MenuId.TB_UserMonthPerformance);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 删除
     */
    @RequestMapping("/toDel")
    @ResponseBody
    public R toDel(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            int delCount = 0;
            //删除
            for (int i = 0; i < idList.size(); i++) {
                R res= tbUserMonthPerformanceService.del(Long.parseLong(idList.get(i)));
                if(res.getCode()==0){
                    delCount ++;
                }
            }
            String backMsg = "成功删除"+delCount+"条！";
            if(idList.size()!=delCount){
                backMsg+="（已生成工资条的信息不能删除）";
            }
            return R.ok(backMsg);
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 弹出框
     */
    @RequestMapping("/searchForModal")
    @ResponseBody
    public LayuiTableVoJA searchForModal(@ModelAttribute TbUserMonthPerformance cond){
        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表TbUserTaxManage
                .addField("(U.UserId + '/' + U.UserName) AS userName")//工号/姓名

                .addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
                .addField("OI.OrgName AS deptName")//部门

                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = U.OrgId")//用户所属机构

                .addLeftJoin("THR_UserArchives UAS ON UAS.UserId = A.UserId")//用户档案表
                .addField("UAS.UserState AS userState")//员工状态

                .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表TbUserMonthPerformanceReport
                .addField("O.OrgName AS orgName");//所属公司

        //只查询绩效申报状态为空的数据
        cond.where("( SELECT COUNT ( 1 ) AS num FROM TB_UserMonthPerformanceReportItem RI WHERE RI.MonthPerformanceId = A.Id) = 0 ");

        cond.setStatus(1);
        //排序
        cond.setOrderby("A.PointMonth DESC");
        cond = commonApiService.dataAuth(MenuId.TB_UserMonthPerformance, cond);

        return commonApiService.searchLay(cond);
    }


    /**
     * 同步员工考勤信息表id
     */
    @RequestMapping("/updateUserAttendanceId")
    @ResponseBody
    public R updateUserAttendanceId(HttpServletRequest request,  @RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            //return tbUserMonthPerformanceService.updateUserAttendanceId(countMonth);
            int count = 0;
            //同步
            for (int i = 0; i < idList.size(); i++) {
                R res= tbUserMonthPerformanceService.updateUserAttendanceIdById(Long.parseLong(idList.get(i)));
                if(res.getCode()==0){
                    count ++;
                }
            }
            String backMsg = "成功同步"+count+"条！";
            return R.ok(backMsg);

        } catch (Exception e) {
            logger.error("同步出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 修改员工考勤状态
     */
    @RequestMapping("/updateAttendanceStatus")
    @ResponseBody
    public R updateAttendanceStatus(HttpServletRequest request, @RequestParam("list") List<String> idList){
        try {
            int count = 0;
            //修改
            for (int i = 0; i < idList.size(); i++) {
                R res= tbUserMonthPerformanceService.updateAttendanceStatus(Long.parseLong(idList.get(i)));
                if(res.getCode()==0){
                    count ++;
                }
            }
            //String backMsg = "成功修改"+count+"条！";
            String backMsg = "修改成功！";
            return R.ok(backMsg);

        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 推送员工工资条信息表
     */
    @RequestMapping("/addUserPaySlip")
    @ResponseBody
    public R addUserPaySlip(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            String resMsg = "";
            for (int i=0;i<idList.size();i++){
                resMsg += "推送的第"+(i+1)+"条信息："+tbUserPaySlipService.addByMonthPerformanceId(Long.parseLong(idList.get(i)))+"</br>";
            }
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("推送出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 弹出框
     */
    @RequestMapping("/searchForModalGjj")
    @ResponseBody
    public LayuiTableVoJA searchForModalGjj(@ModelAttribute TbUserMonthPerformance cond){
        //获取当前年月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        //获取当前时间日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 0);//上个月
        String oldMonth = sdf.format(calendar.getTime());

        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表TbUserTaxManage
            .addField("(U.UserId + '/' + U.UserName) AS userName")//工号/姓名

        .addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
             .addField("OI.OrgName AS deptName")//部门

        .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = U.OrgId")//用户所属机构

        .addLeftJoin("THR_UserArchives UAS ON UAS.UserId = A.UserId")//用户档案表
            .addField("UAS.UserState AS userState")//员工状态

        .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表TbUserMonthPerformanceReport
            .addField("O.OrgName AS orgName")//所属公司
            .addField("A.pointMonth AS payDate")//缴费年月
//            .addField("SUBSTRING(CONVERT(varchar, DATEADD(MONTH,1,A.pointMonth + '-01'), 23),0,8) AS payDate")//缴费年月
        .addLeftJoin("TS_OrganizationAccount oa ON oa.OrgId = U.DeptId AND oa.Status = 1")//部门绑定账号
        .addLeftJoin("THR_OperateCompanyApply THRO ON  THRO.Vgsbm = oa.Vgsbm")
             .addField("THRO.Vgsbm AS vgsbm,THRO.vgsjc AS vgsjc")//运营公司
             .addField("A.id userMonthPerformanceId")//月度绩效id
        .addLeftJoin("TB_UserJobLevelManage ulm ON ulm.id = A.UserJobLevelManageId")//职级管理

        .addLeftJoin("TB_ProvidentFund P ON P.id = ulm.AccumulationFundId AND P.Status = 1")//公积金管理表
            .addField("P.HousingPfBase AS housingPfBase")//公积金基数
            .addField("P.PfUnitMonth AS accumulationFundCompany")//公积金（单位）/月
            .addField("P.PfIndividualMonth AS accumulationFundPersonal")//公积金（个人）/月
        ;

        //只查询公积金付款未被调用的数据
        cond.where("( SELECT COUNT ( 1 ) AS num FROM TB_ReservedPayItem rpi WHERE rpi.UserMonthPerformanceId = A.Id) = 0 AND A.pointMonth = '" + oldMonth + "'");

        cond.setStatus(1);
        //排序
        cond.setOrderby("A.PointMonth DESC");

        return commonApiService.searchLay(cond);
    }


    /**
     * 弹出框医保使用
     */
    @RequestMapping("/searchForModalYb")
    @ResponseBody
    public LayuiTableVoJA searchForModalYb(@ModelAttribute TbUserMonthPerformance cond){
        //获取当前年月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        //获取当前时间日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 0);//上个月
        String oldMonth = sdf.format(calendar.getTime());

        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表TbUserTaxManage
                .addField("(U.UserId + '/' + U.UserName) AS userName")//工号/姓名

        .addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
                .addField("OI.OrgName AS deptName")//部门

        .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = U.OrgId")//用户所属机构

        .addLeftJoin("THR_UserArchives UAS ON UAS.UserId = A.UserId")//用户档案表
                .addField("UAS.UserState AS userState")//员工状态

        .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表TbUserMonthPerformanceReport
                .addField("O.OrgName AS orgName")//所属公司
                .addField("A.pointMonth AS payDate")//缴费年月
//                .addField("SUBSTRING(CONVERT(varchar, DATEADD(MONTH,1,A.pointMonth + '-01'), 23),0,8) AS payDate")//缴费年月
        .addLeftJoin("TS_OrganizationAccount oa ON oa.OrgId = U.DeptId AND oa.Status = 1")//部门绑定账号
        .addLeftJoin("THR_OperateCompanyApply THRO ON  THRO.Vgsbm = oa.Vgsbm")
                .addField("THRO.Vgsbm AS vgsbm,THRO.vgsjc AS vgsjc")//运营公司
                .addField("A.id userMonthPerformanceId")//月度绩效id
        .addLeftJoin("TB_UserJobLevelManage ulm ON ulm.id = A.UserJobLevelManageId")//职级管理
        .addLeftJoin("TB_MedicalInsurance Mi ON Mi.id = ulm.MedicalInsuranceId AND Mi.Status = 1")//医保管理
                .addField("Mi.miUnitMoonth AS healthCompany")//医疗保险（单位）
                .addField("Mi.miIndividualMonth AS healthPersonal")//医疗保险（个人）
                .addField("Mi.miUnitMonth AS birthCompany")//生育保险（单位）
        ;

        //只查询医保付款未被调用的数据
        cond.where("( SELECT COUNT ( 1 ) AS num FROM TB_MedicarePayItem rpi WHERE rpi.UserMonthPerformanceId = A.Id) = 0 AND A.pointMonth = '" + oldMonth + "'");

        cond.setStatus(1);
        //排序
        cond.setOrderby("A.PointMonth DESC");

        return commonApiService.searchLay(cond);
    }

    /**
     * 弹出框社保使用
     */
    @RequestMapping("/searchForModalSb")
    @ResponseBody
    public LayuiTableVoJA searchForModalSb(@ModelAttribute TbUserMonthPerformance cond){
        //获取当前年月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        //获取当前时间日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 0);//上个月
        String oldMonth = sdf.format(calendar.getTime());

        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表TbUserTaxManage
                .addField("(U.UserId + '/' + U.UserName) AS userName")//工号/姓名

                .addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
                .addField("OI.OrgName AS deptName")//部门

                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = U.OrgId")//用户所属机构

                .addLeftJoin("THR_UserArchives UAS ON UAS.UserId = A.UserId")//用户档案表
                .addField("UAS.UserState AS userState")//员工状态

                .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表TbUserMonthPerformanceReport
                .addField("O.OrgName AS orgName")//所属公司
                .addField("A.pointMonth AS payDate")//缴费年月
//                .addField("SUBSTRING(CONVERT(varchar, DATEADD(MONTH,1,A.pointMonth + '-01'), 23),0,8) AS payDate")//缴费年月
                .addLeftJoin("TS_OrganizationAccount oa ON oa.OrgId = U.DeptId AND oa.Status = 1")//部门绑定账号
                .addLeftJoin("THR_OperateCompanyApply THRO ON  THRO.Vgsbm = oa.Vgsbm")
                .addField("THRO.Vgsbm AS vgsbm,THRO.vgsjc AS vgsjc")//运营公司
                .addField("A.id userMonthPerformanceId")//月度绩效id
                .addLeftJoin("TB_UserJobLevelManage ulm ON ulm.id = A.UserJobLevelManageId")//职级管理
                .addLeftJoin("TB_SocialSecurity ss ON ss.id = ulm.SocialSecurityId AND ss.Status = 1")//社保管理
                .addField("ss.piUnitMonth AS retirementCompany")//养老保险（单位）
                .addField("ss.piIndividualMonth AS retirementPersonal")//养老保险（个人）
                .addField("ss.uiUnitMonth AS loseWorkCompany")//失业保险（单位）
                .addField("ss.uiIndividualMonth AS loseWorkPersonal")//失业保险（个人）
                .addField("ss.wiiUnitMonth AS injuryCompany")//工伤保险（单位）
        ;

        //只查询医保付款未被调用的数据
        cond.where("( SELECT COUNT ( 1 ) AS num FROM TB_SocialSecurityPayItem rpi WHERE rpi.UserMonthPerformanceId = A.Id) = 0 AND A.pointMonth = '" + oldMonth + "'");

        cond.setStatus(1);
        //排序
        cond.setOrderby("A.PointMonth DESC");

        return commonApiService.searchLay(cond);
    }

}